package com.example.launibleplugin.model

import com.google.gson.annotations.SerializedName

/**
 * 蓝牙设备数据模型
 * Function: 表示扫描到的蓝牙设备信息
 * Parameter: 设备基本信息和连接状态
 * Note: 用于设备列表展示和连接管理
 */
data class BluetoothDevice(
    @SerializedName("device_id")
    val deviceId: String,
    
    @SerializedName("device_name")
    val deviceName: String?,
    
    @SerializedName("mac_address")
    val macAddress: String,
    
    @SerializedName("device_type")
    val deviceType: String = "respiratory_device",
    
    @SerializedName("signal_strength")
    var signalStrength: Int = 0,
    
    @SerializedName("is_paired")
    val isPaired: Boolean = false,
    
    @SerializedName("is_connected")
    val isConnected: Boolean = false,
    
    @SerializedName("last_seen")
    val lastSeen: Long = System.currentTimeMillis(),
    
    @SerializedName("services")
    val services: List<String> = emptyList()
) {
    /**
     * Function: 获取设备显示名称
     * Return: String - 设备的原始名称或优化后的名称
     * Note: 优先显示设备原始名称，只在名称无效时才使用智能识别
     */
    fun getDisplayName(): String {
        // 检查设备名称是否有效（非空且不是MAC地址格式）
        val originalName = deviceName?.takeIf { 
            it.isNotBlank() && 
            !it.matches(Regex("[0-9A-Fa-f:]{17}")) && 
            !it.matches(Regex("[0-9A-Fa-f]{12}")) &&
            it.length > 2
        }
        
        // 如果有有效的原始名称，直接使用，但为呼吸家设备添加特殊标识
        if (originalName != null) {
            return if (isRespiratoryDevice()) {
                "🫁 $originalName"
            } else {
                originalName
            }
        }
        
        // 只有在没有有效原始名称时才使用智能识别
        return when {
            // 呼吸家设备识别
            isRespiratoryDevice() -> {
                "🫁 呼吸家设备 (${macAddress.takeLast(8)})"
            }
            // 根据MAC地址前缀识别厂商
            macAddress.startsWith("FC:58:FA", ignoreCase = true) ||
            macAddress.startsWith("34:CE:00", ignoreCase = true) -> {
                "📱 小米设备 (${macAddress.takeLast(8)})"
            }
            macAddress.startsWith("DC:A6:32", ignoreCase = true) ||
            macAddress.startsWith("F0:18:98", ignoreCase = true) -> {
                "🍎 苹果设备 (${macAddress.takeLast(8)})"
            }
            macAddress.startsWith("48:F0:7B", ignoreCase = true) ||
            macAddress.startsWith("AC:37:43", ignoreCase = true) -> {
                "📱 华为设备 (${macAddress.takeLast(8)})"
            }
            macAddress.startsWith("C4:07:2F", ignoreCase = true) ||
            macAddress.startsWith("08:D4:2B", ignoreCase = true) -> {
                "📱 三星设备 (${macAddress.takeLast(8)})"
            }
            // 无法识别的设备
            else -> {
                "❓ 未知设备 (${macAddress.takeLast(8)})"
            }
        }
    }
    
    /**
     * Function: 判断是否为呼吸家设备
     * Return: Boolean - 是否为目标设备
     * Note: 根据设备名称或IMEI格式判断
     */
    fun isRespiratoryDevice(): Boolean {
        val name = deviceName?.lowercase() ?: ""
        
        // 检查是否包含呼吸家相关关键词
        val hasKeyword = name.contains("呼吸家") || name.contains("respiratory") || name.contains("huxijia")
        
        // 检查是否符合呼吸家设备IMEI格式（10位字符，通常以A或B开头）
        val isImeiFormat = deviceName?.let { 
            it.length == 10 && 
            (it.startsWith("A", ignoreCase = true) || it.startsWith("B", ignoreCase = true)) &&
            it.substring(1).all { char -> char.isDigit() }
        } ?: false
        
        return hasKeyword || isImeiFormat
    }
    
    /**
     * Function: 获取信号强度描述
     * Return: String - 信号强度文本
     * Note: 将RSSI值转换为用户友好的描述
     */
    fun getSignalStrengthDescription(): String {
        return when {
            signalStrength >= -50 -> "强"
            signalStrength >= -70 -> "中"
            signalStrength >= -90 -> "弱"
            else -> "很弱"
        }
    }
    
    /**
     * Function: 获取设备类型标识
     * Return: String - 设备类型标识
     * Note: 用于UI中的设备分类显示
     */
    fun getDeviceTypeLabel(): String {
        val name = deviceName?.takeIf { it.isNotBlank() }
        
        return when {
            isRespiratoryDevice() -> "呼吸家设备"
            name?.contains("Xiaomi", ignoreCase = true) == true || 
            name?.contains("Mi ", ignoreCase = true) == true -> "小米设备"
            name?.contains("iPhone", ignoreCase = true) == true ||
            name?.contains("iPad", ignoreCase = true) == true ||
            name?.contains("AirPods", ignoreCase = true) == true ||
            name?.contains("Apple", ignoreCase = true) == true -> "苹果设备"
            name?.contains("HUAWEI", ignoreCase = true) == true ||
            name?.contains("Honor", ignoreCase = true) == true -> "华为设备"
            name?.contains("Samsung", ignoreCase = true) == true ||
            name?.contains("Galaxy", ignoreCase = true) == true -> "三星设备"
            name?.contains("OPPO", ignoreCase = true) == true ||
            name?.contains("OnePlus", ignoreCase = true) == true -> "OPPO设备"
            name?.contains("vivo", ignoreCase = true) == true -> "vivo设备"
            name?.contains("Headphone", ignoreCase = true) == true ||
            name?.contains("Earphone", ignoreCase = true) == true ||
            name?.contains("Buds", ignoreCase = true) == true ||
            name?.contains("TWS", ignoreCase = true) == true -> "蓝牙耳机"
            name?.contains("Speaker", ignoreCase = true) == true ||
            name?.contains("Sound", ignoreCase = true) == true -> "蓝牙音箱"
            name?.contains("Car", ignoreCase = true) == true ||
            name?.contains("Auto", ignoreCase = true) == true -> "车载设备"
            name != null -> "蓝牙设备"
            else -> "未知设备"
        }
    }
}